import React from "react";
import api from "src/http/api";

import { Upload, UploadProps } from "@formily/antd";
import { Modal, message, ModalProps } from "antd";
import { RcFile } from "antd/lib/upload/interface";
import { PlusOutlined } from "@ant-design/icons";

import styles from "./index.scss";

const { useState } = React;

interface Preview {
  previewVisible: boolean;
  previewImage: string | undefined;
  previewTitle: string | undefined;
}

const AvatarUpload: React.FC = (props) => {
  const [preview, setPreview] = useState({} as Preview);

  function getBase64(file: RcFile) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }

  const uploadProps: UploadProps = {
    action: api.uploadAvatar(),
    listType: "picture-card",
    maxCount: 1,
    // TODO: 这里的headers后面要改成加cookie或者session
    headers: { authorization: "authorization-text" },

    beforeUpload: (file) => {
      const isImage = file.type.indexOf("image") !== -1;
      if (!isImage) {
        message.error(`${file.name} is not a image file`);
      }
      return isImage;
    },

    onPreview: async (file) => {
      if (!file.url && !file.preview) {
        file.preview = `${await getBase64(file.originFileObj as RcFile)}`;
      }

      const fileUrl = `${file.url?.substring(
        file.url.indexOf("_") + 1,
        file.url.lastIndexOf("_")
      )}${file.url?.substring(file.url.lastIndexOf("."))}`;

      setPreview({
        previewImage: file.url || file.preview,
        previewVisible: true,
        previewTitle: file.name || fileUrl,
      });
    },
  };

  const modalProps: ModalProps = {
    visible: preview.previewVisible,
    title: preview.previewTitle,
    footer: null,
    onCancel: () => setPreview({ ...preview, previewVisible: false }),
  };

  return (
    <>
      <Upload
        {...props}
        {...uploadProps}
        listType="picture-card"
        className={(styles as any).picture}
      >
        <div>
          <PlusOutlined />
          <div style={{ marginTop: 8 }}>Upload</div>
        </div>
      </Upload>

      <Modal {...modalProps}>
        <img alt="" style={{ width: "100%" }} src={preview.previewImage} />
      </Modal>
    </>
  );
};

export default AvatarUpload;
